package com.xinyi.shicihui.service.impl;

import com.xinyi.shicihui.dao.ShiciDao;
import com.xinyi.shicihui.dao.ShiciInfoDao;
import com.xinyi.shicihui.dao.TagDao;
import com.xinyi.shicihui.pojo.entity.Shici;
import com.xinyi.shicihui.pojo.entity.ShiciInfo;
import com.xinyi.shicihui.pojo.entity.Shiren;
import com.xinyi.shicihui.pojo.entity.Tag;
import com.xinyi.shicihui.pojo.vo.ShiciDetailVo;
import com.xinyi.shicihui.pojo.vo.ShiciInfoVo;
import com.xinyi.shicihui.pojo.vo.ShiciVo;
import com.xinyi.shicihui.pojo.vo.TagVo;
import com.xinyi.shicihui.service.ShiciService;
import com.xinyi.shicihui.utils.BeanMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author xinyi
 * @desc 诗词信息服务实现
 * @date 2022/1/26
 */
@Service
public class ShiciServiceImpl implements ShiciService {

    @Autowired
    private ShiciDao shiciDao;

    @Autowired
    private ShiciInfoDao shiciInfoDao;

    @Autowired
    private TagDao tagDao;

    @Override
    public Page<Shici> pageQuery(Integer page, Integer size, String dynastyId, String tagId) {
        Shici shici = new Shici();
        shici.setDynastyId(dynastyId);
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<Shici> example = Example.of(shici, matcher);

        return "-1".equals(dynastyId) ? shiciDao.findAll(PageRequest.of(page, size)) :
                shiciDao.findAll(example, PageRequest.of(page-1, size));
    }

    @Override
    public ShiciDetailVo detail(String id) {
        Optional<Shici> shiciOptional = shiciDao.findById(id);
        if (!shiciOptional.isPresent()) {
            return new ShiciDetailVo();
        }
        Shici shici = shiciOptional.get();
        ShiciVo shiciVo = BeanMapperUtils.map(shiciOptional.get(), ShiciVo.class);
        List<String> tags = Arrays.stream(shici.getTags().split(",")).collect(Collectors.toList());
        List<Tag> tagList = tagDao.findByTagIn(tags);
        shiciVo.setTagList(BeanMapperUtils.mapList(tagList, TagVo.class));
        List<ShiciInfo> infos = shiciInfoDao.findByShiCiId(id);
        ShiciDetailVo shiciDetailVo = new ShiciDetailVo();
        shiciDetailVo.setShici(shiciVo);
        shiciDetailVo.setInfo(BeanMapperUtils.mapList(infos, ShiciInfoVo.class));
        return shiciDetailVo;
    }


}
